import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { DomSanitizer } from '@angular/platform-browser';

declare var ui: any;
declare var base: any;
declare var form: any;
declare var security: any;

@Component({
  templateUrl: './bpm.define.info.html'
})
export class BpmDefineInfoComponent implements OnInit {

  // 当前数据
  fs: any;
  ffs: any = null;

  config: any = {};
  taskConfig: any = {};

  imageUrl: string;
  imageSrc: any;
  menu = null;

  pRole: any;
  taskDic: any;

  constructor(
    public route: ActivatedRoute,
    private modalService: NzModalService,
    private http: HttpClient,
    private domSanitizer: DomSanitizer) {
    this.menu = new ui.TabService('bpm', 's');
    this.menu.setTab('main');
    // 注册表单
    this.fs = new form.FormSideSimpleService('bpmconfig', {
      orderObject: { actDefName: 0, version: 0 },
      keyField: 'id',
      randomFields: ['id'],
      foreignKey: 'group'
    });
    // 文件服务
    this.ffs = new form.FileService();
    this.pRole = new form.DictionaryService('p_role');
    this.pRole.loadAll();
    this.taskDic = new form.DictionaryService('b_tasktype');
  }

  ngOnInit() {
    this.initData();

    // 浏览器关闭监听
    window.onbeforeunload = () => {
      // tslint:disable-next-line: deprecation
      const e: any = window.event;
      e.returnValue = ('请确认已保存，是否离开？');
      return e;
    };
  }

  initData() {
    let id = '-1';
    this.route.queryParams.subscribe((res) => {
      if (res.id) {
        id = res.id;
      }
    });
    this.fs.editRowByKey(id, () => {
      this.config = this.fs.er;
      this.imageUrl = base.BaseService.getHostUrl()
        + '/bpmimage/loadImage/'
        + this.config.actDefID
        + '/' + this.config.version
        + '/' + this.config.bpmType
        + '?r=' + base.BaseService.getGUID();
      const jwts = security.SecurityService.jwt;
      this.http.get(this.imageUrl, {
        headers: new HttpHeaders({ jwt: jwts }),
        responseType: 'blob', observe: 'response'
      }).subscribe(rs => {
        const pdfFile = new Blob([rs.body], { type: 'image/png' });
        const datalocalURL = window.URL.createObjectURL(pdfFile);
        this.imageSrc = this.domSanitizer.bypassSecurityTrustResourceUrl(datalocalURL);
      });
    });
  }

  changeTask(task) {
    this.menu.setTab('task');
    this.taskConfig = task;
  }

  save() {
    this.fs.save(this.fs.er, (data) => {
      this.modalService.success({
        nzTitle: '系统提示',
        nzContent: '保存成功！'
      });
    }, (error) => {
      this.modalService.error({
        nzTitle: '系统提示',
        nzContent: '保存失败！'
      });
    });
  }

  close() {
    window.close();
    // this.modalService.confirm({
    //   nzTitle: '系统提示',
    //   nzContent: '请确认已保存，是否关闭？',
    //   nzOnOk: () => {
    //     window.close();
    //   }
    // });
  }
}
